package com.eascs.demand.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import jodd.util.StringUtil;

import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.eascs.admin.api.form.UserDemandForm;
import com.eascs.admin.common.dao.BaseO2oDao;
import com.eascs.admin.common.utils.StringUtils;
import com.eascs.admin.o2o.internal.util.StatusContexts;
import com.eascs.app.dao.PageResult;
import com.eascs.app.dao.SqlPageQuery;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.demand.entity.FormDemandEntity;
import com.eascs.demand.entity.MainApply;
import com.eascs.demand.entity.UserDemand;
import com.eascs.workflow.common.entity.sys.ActOrgEntity;
import com.eascs.workflow.common.service.sys.SysOrgService;
import com.eascs.workflow.common.vo.ModelResult;
@Service
public class DemandService extends BaseO2oDao{
	private static Logger log = LoggerFactory.getLogger(DemandService.class);
	@Reference
	SysOrgService sysOrgService;
	@Transactional(transactionManager = "o2oTransactionManager")
	public void insertDemand(UserDemand demand) {
		this.insert(demand);
	}
	
	//插入主表
	@Transactional(transactionManager = "o2oTransactionManager")
	public void insertMainApply(MainApply mainApply) {
		this.insert(mainApply);
	}
	@Transactional(transactionManager = "o2oTransactionManager")
	public void insertAll(UserDemand demand,MainApply mainApply){
		this.insert(demand);
		this.insert(mainApply);
	}
	@Transactional(transactionManager = "o2oTransactionManager")
	public void insertDemandAll(UserDemandForm demand,MainApply mainApply){
		this.insert(demand);
		this.insert(mainApply);
	}
	
	//修改主表
	@Transactional(transactionManager = "o2oTransactionManager")
	public void updateMainApplyById(MainApply mainApply) {
		this.updateById(mainApply);
	}
	//修改需求信息
	@Transactional(transactionManager = "o2oTransactionManager")
	public int updateDemandApply(UserDemand userDemand) {
		return this.updateById(userDemand);
	}
	@Transactional(transactionManager = "o2oTransactionManager")
	public void updateAll(MainApply mainApply,UserDemand userDemand){
		this.updateById(mainApply);
		this.updateById(userDemand);
	}
	@Transactional(transactionManager = "o2oTransactionManager")
	public int delAll(MainApply mainApply,UserDemand userDemand){
		int num=0;
		if (mainApply!=null) {
			mainApply.setIslock("Y");
			num=this.updateById(mainApply);
		}
		if (userDemand!=null) {
			userDemand.setIslock("Y");
			num=this.updateById(userDemand);
		}
		return num;
	}
	//删除需求信息
	@Transactional(transactionManager = "o2oTransactionManager")
	public int delDemandApply(UserDemand userDemand) {
		return this.deleteByIdWithEntity(userDemand);
	}
	
	//根据id找到需求单
	public UserDemand getUserDemandById(String id) {
		return this.getById(UserDemand.class, id);
	}
	
	public UserDemand getUserDemandByBillcode(String billCode) {
		String id = this.findString("select id from user_demand where bill_code=?", billCode);
		return getUserDemandById(id);
	}
	
	public String getLtdByUserNo(String userNo) {
		//ModelResult<ActOrgEntity> modelResult = sysOrgService.getActOrgByUserNo(userNo);
		ModelResult<List<ActOrgEntity>> modelResult =  sysOrgService.getPlatformWithUser(userNo);
		log.info("workflow返回的用户平台结果集为：[{}]", modelResult.toString());
		ActOrgEntity actOrgEntity = modelResult.getModel().get(0);
		return actOrgEntity.getUnitNo();
	}
	
	public PageResult<Object[]> findDemandDataListEntityById(String demand_no) {
		String sql = "select datalist_no,datalist_name,original_name,creat_or,creat_date,update_time from  demand_datalist where is_delete=? and demand_no=? ORDER BY update_time desc";
		SqlPageQuery<Object[]> pageQuery = new SqlPageQuery<>(Object[].class, Integer.MAX_VALUE, 0);
		pageQuery.addParam(StatusContexts.O2O_NO);
		pageQuery.addParam(demand_no);
		pageQuery.setQuerySql(sql);
		return this.findDataWithPage(pageQuery);
	}
	
	public PageResult<Object[]> findByPageList(FormDemandEntity demandEntity) {
		SqlPageQuery<Object[]> pageQuery = new SqlPageQuery<>(Object[].class, demandEntity.getPageSize(), demandEntity.getShowO2oPage());
		StringBuffer querySql = new StringBuffer();
		querySql.append(" select ocb.id,ocb.islock,ocb.bill_code,ocb.title,ocb.demand_type,ocb.demand_user,ocb.dep_name,ocb.create_date,ocb.due_date,ocb.creator,f.bill_status,f.end_date");
		querySql.append(" from user_demand ocb left join main_apply f on ocb.id = f.expand_id where ");
		if(demandEntity.isQueryAll()){
			querySql.append(" ocb.islock != 'Y' ");
		} else {
			querySql.append(" /**DATA_PERMISSION(f.LTD)**/ ocb.islock != 'Y' ");
			if (!StringUtil.isEmpty(demandEntity.getUserId())) {
				querySql.append(" AND ocb.creator_id = ? ");
				pageQuery.addParam(demandEntity.getUserId());
			}
		}
		if (!StringUtil.isEmpty(demandEntity.getBill_code())) {
			querySql.append(" AND ocb.bill_code like ? ");
			pageQuery.addLikeParam(demandEntity.getBill_code().trim());
		}
		if (!StringUtil.isEmpty(demandEntity.getDemandUser())) {
			querySql.append(" AND ocb.demand_user like ? ");
			pageQuery.addLikeParam(demandEntity.getDemandUser().trim());
		}
		if (!StringUtil.isEmpty(demandEntity.getTitle())) {
			querySql.append(" AND ocb.title like ? ");
			pageQuery.addLikeParam(demandEntity.getTitle().trim());
		}
		if (!StringUtil.isEmpty(demandEntity.getKeyWord())) {
			querySql.append(" AND (ocb.title like '%"+demandEntity.getKeyWord().trim()+"%' or ocb.demand_text like '%"+demandEntity.getKeyWord().trim()+"%')");
		}
		if(StringUtils.isNotEmpty(demandEntity.getBeganTime())){
			querySql.append(" AND ocb.create_date >= ?");
			SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd");
			try {
				pageQuery.addParam(s.parse(demandEntity.getBeganTime()));
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if(StringUtils.isNotEmpty(demandEntity.getEndTime())){
			querySql.append(" AND ocb.create_date <= ?");
			SimpleDateFormat s=new SimpleDateFormat("yyyy-MM-dd");
			try {
				Date parse = s.parse(demandEntity.getEndTime());
				Calendar date = Calendar.getInstance();
				date.setTime(parse);
				date.set(Calendar.DATE, date.get(Calendar.DATE) + 1);
				Date endDate = s.parse(s.format(date.getTime()));
				pageQuery.addParam(endDate);
			} catch (ParseException e) {
				e.printStackTrace();
			}
		}
		if(StringUtils.isNotEmpty(demandEntity.getApplyStatus())){
			querySql.append(" AND f.bill_status = ?");
			pageQuery.addParam(demandEntity.getApplyStatus());
		}
		querySql.append(" ORDER BY ocb.update_date DESC ");
		pageQuery.setQuerySql(querySql.toString());
		return this.findDataWithPage(pageQuery);
	}
}
